<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue'
import ArticleItem from '../components/article/ArticleItem.vue'
import Label from '../components/article/Label.vue'
import Category from '../components/category/Category.vue'
import request from '../api/index'
const proxy = getCurrentInstance()?.proxy
const titleFunction = [
  {
    type: 'search',
    placeholder: '请输入标题/简介',
  },
  {
    type: 'button',
    text: '新建',
    typeButton: '',
  }
]
const url = ref({
  get:'/admin/article/searchArticle',
  getCategory: '/admin/category/searchCategory',
  getLabel: '/admin/label/searchLabel'
})
const params = ref({
  articleId: undefined,
  categoryId: undefined,
  keyword: undefined,
  labels: undefined,
  type: 0
})
const pagination = ref({
    currentPage: 1,
    pageSize: 4,
    totalCount: 0,
    totalPages: 1
})
const categoryList = ref([])
const articleList = ref([])
const category = ref(null) 
const labelList = ref([])

onMounted(() => { 
  getDataList()
  getLableList()
})

const getDataList = body => {
  request.post(url.value.get, {
    page: pagination.value.currentPage,
    pageSize: pagination.value.pageSize,
    ...params.value,
    ...body
  }).then(res => {
    if (res.data.status ==='success') {
      articleList.value = res.data.data
      pagination.value = res.data.pagination
    } else {
      articleList.value = []
      if (res.data.errCode >= 500 ) {
        proxy.$message({ type: 'error', duration: 1000,  message: res.data.message })
      }
    }
  })

  request.get(url.value.getCategory + '?type=1').then(res => {
    if (res.data.status ==='success') {
      categoryList.value = res.data.data
    } else {
      categoryList.value = []
      if (res.data.errCode >= 500 ) {
        proxy.$message({ type: 'error', duration: 1000,  message: res.data.message })
      } else {
        proxy.$message({ type: 'warning', duration: 1000,  message: res.data.message })
      }
    }
  }) 

  getLableList()
}

const getLableList = (id, type = 0) => {
  let labels
  let allLabels
  request.get(url.value.getLabel + '?type=' + type).then(res => {
    if (res.data.status ==='success') {
      allLabels = res.data.allLabels
      labels = res.data.labels
      labelList.value = allLabels.map(item => {
        for (let i = 0; i < labels.length; i++) {
          if (item.ID === labels[i].ID) {
            item.articleCount = labels[i].articleCount
            break
          } else {
            item.articleCount = 0
          }
        }
        return item
      }) 
    } else {
      allLabels =  []
      labels = []
      if (res.data.errCode >= 500 ) {
        proxy.$message({ type: 'error', duration: 1000,  message: res.data.message })
      } else {
        proxy.$message({ type: 'warning', duration: 1000,  message: res.data.message })
      }
    }
  })
}

const selectCategory = id => {
  pagination.value.currentPage = 1
  params.value.categoryId = id
  getDataList()
}
const updateDate = id => {
  if(id) {
    if (id === params.value.categoryId) {
      category.value.changeCategory(-1)
    }
  }
  getDataList()
}

const lUpdateDate = id => {
  if(id) { 
    if (params.value.labels.includes(id)) {
      params.value.labels.splice(params.value.labels.indexOf(id), 1)
      pagination.value.currentPage = 1
      getDataList()
    }
  }
  getDataList()
}

const aUpdateDate = id => {
  getDataList()
}

const getCateName = id => {
  return categoryList.value.find(item => item.ID === id)?.category_name || '未分类'
}

const getLabelNames = ids => {
  let labelNames = []
  ids?.forEach(item => {
    labelNames.push(labelList.value.find(label => label.ID == item)?.name)
  })
  return labelNames.filter(item => item != null)
}

const sizeChange = (page) => {
  pagination.value.currentPage = page
  getDataList()
}

const selectLabel = ids => {
  pagination.value.currentPage = 1
  params.value.labels = ids
  getDataList()
}
const inputKeywords = keyword => {
  pagination.value.currentPage = 1
  params.value.keyword = keyword
  getDataList()
}

</script>

<template>
<div class="acticle-view">
  <yk-space dir="vertical" :size="24">
    <top-title title="博客文章" :titleFunction="titleFunction" @search="inputKeywords" :categoryList="categoryList" />
    <Category :categoryList="categoryList" @selectCategory="selectCategory" :type="1" @updateDate="updateDate" ref="category" />
    <yk-space :size="24" style="width:100%">
      <yk-space :size="16" dir="vertical" style="width:100%" >
        <article-item v-if="articleList.length > 0" v-for="(item, index) in articleList " :key="item.ID" :labelNames="getLabelNames(item.label_id)" :articleInfo="item" :categoryName="getCateName(item.category_id)" @aUpdateDate="aUpdateDate"  />
        <yk-pagination @change="sizeChange" style="margin-top: 12px;width:100%;justify-content: flex-end;"  v-if="articleList.length > 0" :default-page-size="pagination.pageSize" v-model:current="pagination.currentPage" :total="pagination.totalCount"/>
        <yk-empty v-else style="width:100%;">
          <template #description>
            暂无文章
          </template>
        </yk-empty>
      </yk-space>
      <div style="width:400px;">
        <Label :labelList="labelList" @selectLabel="selectLabel" @lUpdateDate="lUpdateDate" />
      </div>
    </yk-space>
  </yk-space>
</div>
</template>

<style scoped lang='less'>
.acticle-view {
  padding: 32px 32px 32px 232px;
  width: 100%;
  background-color: @bg-color-m;
}
</style>